package com.cloud.common.magic_init.handler;

import com.cloud.common.domain.Result;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.ResultProvider;
import org.ssssssss.magicapi.modules.db.BoundSql;
import org.ssssssss.magicapi.modules.db.dialect.Dialect;
import org.ssssssss.magicapi.modules.db.model.Page;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Magic-api 统一请求封装
 *
 * @author yzj
 */
@Component
public class MagicDataProvider implements ResultProvider, Dialect {

    // 定义返回结果,默认返回JsonBean
    @Override
    public Object buildResult(RequestEntity entity, int code, String message, Object data) {
        return Result.data(code, message, data);
    }

    // 定义分页返回结果,该项会被封装在Json结果内,此方法可以不覆盖,默认返回PageResult
    @Override
    public Object buildPageResult(RequestEntity requestEntity, Page page,
                                  long total, List<Map<String, Object>> data) {
        Map<String, Object> tableMap = new LinkedHashMap<>();
        Map<String, Object> paramMap = requestEntity.getParameters();
        if (ObjectUtils.isNotEmpty(paramMap)) {
            int pageNum = 0;
            int pageSize = 0;
            if (paramMap.containsKey("pageNum") || paramMap.containsKey("pageSize")) {
                Integer.parseInt(paramMap.get("pageNum").toString());
                Integer.parseInt(paramMap.get("pageSize").toString());
            } else {
                return Result.error("分页参数不能为空");
            }
            tableMap.put("current", pageNum);
            tableMap.put("size", pageSize);
        }
        tableMap.put("total", total);
        tableMap.put("rows", data);
        return tableMap;
    }

    // 全局异常拦截
    @Override
    public Object buildException(RequestEntity entity, Throwable throwable) {
        return buildResult(entity, Result.ERROR, "系统内部出现错误" + throwable.getMessage());
    }

    @Override
    public boolean match(String jdbcUrl) {
        // 根据JDBC_URL判断是否需要处理
        boolean result = false;
        if (jdbcUrl.contains(":mysql:")) {
            result = true;
        }
        if (jdbcUrl.contains(":TAOS-RS:")) {
            result = true;
        }
        return result;
    }

    @Override
    public String getPageSql(String sql, BoundSql boundSql, long offset, long limit) {
        boundSql.addParameter(offset);
        boundSql.addParameter(limit);
        return sql + " limit ?,?";
    }

}
